/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.dto.InvitationRecord;
import com.yami.shop.bean.model.PostRecord;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.UserLikeRecordMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.security.enums.App;
import com.yami.shop.security.service.YamiUser;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.PostRecordService;
import com.yami.shop.service.UserLikeRecordService;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;

import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.app.param.UserInfoParam;
import com.yami.shop.bean.model.User;
import com.yami.shop.service.UserService;

import cn.hutool.extra.emoji.EmojiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/p/user")
@Api(tags = "用户接口")
@AllArgsConstructor
public class UserController {

    private final UserService userService;

    private final MapperFacade mapperFacade;

    private final CacheManagerUtil cacheManagerUtil;

    private final ConsumerTokenServices consumerTokenServices;

    private final PostRecordService postRecordService;

    private final UserLikeRecordMapper userLikeRecordMapper;
    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "查看用户信息", notes = "根据用户ID（userId）获取用户信息")
    public ResponseEntity<UserDto> userInfo() throws IOException {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserDto userDto = mapperFacade.map(user, UserDto.class);
        Date now = new Date();
        if(userDto.getRegGiftEndtime() != null){
            if(now.before(userDto.getRegGiftEndtime())){
                userDto.setIsOnTerm(1);
            }else {
                userDto.setIsOnTerm(2);
            }
        }

        if (userDto.getInvGiftEndtime() != null){
            if(now.before(userDto.getInvGiftEndtime())){
                userDto.setInvIsOnTerm(1);
            }else {
                userDto.setInvIsOnTerm(2);
            }
        }

        if (userDto.getInvPleEndtime() != null){
            if(now.before(userDto.getInvPleEndtime())){
                userDto.setPleIsOnTerm(1);
            }else {
                userDto.setPleIsOnTerm(2);
            }
        }

        if(userDto.getOpenid() != null){
            userDto.setIsWx(1);
        }else {
            userDto.setIsWx(0);
        }


        userDto.setMyLikeCount(userLikeRecordMapper.countMyLike(userId));
        return ResponseEntity.ok(userDto);
    }

    @PutMapping("/setUserInfo")
    @ApiOperation(value = "设置用户信息", notes = "设置用户信息")
    public ResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user =mapperFacade.map(userInfoParam,User.class);
        user.setUserId(userId);

        user.setIntroduction(userInfoParam.getIntroduction());
        user.setWxId(userInfoParam.getWxId());
        if(userInfoParam.getNickName()!=null){
            user.setNickName(EmojiUtil.toAlias(userInfoParam.getNickName()));
        }
        userService.updateById(user);
        String cacheKey = App.MINI.value() + StrUtil.COLON + SecurityUtils.getUser().getBizUserId();
        cacheManagerUtil.evictCache("yami_user", cacheKey);
        return ResponseEntity.ok(null);
    }

    @GetMapping("/invRecord")
    @ApiOperation(value = "查看邀请记录",notes = "查看邀请记录")
    public ResponseEntity<List<InvitationRecord>> getInvRecord(){
        String userId = SecurityUtils.getUser().getUserId();
        return ResponseEntity.ok(mapperFacade.mapAsList(userService.getInvRecord(userId),InvitationRecord.class));
    }

    /**
     * 退出登录,并清除redis中的token
     **/
    @GetMapping("/logout")
    public Boolean removeToken(HttpServletRequest httpRequest) {
        String authorization = httpRequest.getHeader("authorization");
        String token = authorization.replace("bearer", "");
        return consumerTokenServices.revokeToken(token);
    }



}
